import re
from django import http
from django.http import response
from django.shortcuts import render, redirect
from django.views import View
from pure_pagination import Paginator

from operation.models import UserAsk, UserFavorite
from organization.models import CourseOrg, Teacher, CityDict
from courses.models import Course


# 展示校区列表页
class OrgListView(View):
    def get(self, request):
        # 获取查询参数
        ct = request.GET.get('ct')
        city_id = request.GET.get('city')

        # 根据类别和地区筛选学校
        if ct is None or ct == '':
            ct = ''
            if city_id is None or city_id == '':
                city_id = ''
                orgs_list = CourseOrg.objects.all().order_by('id')
            else:
                orgs_list = CourseOrg.objects.filter(city_id=city_id).order_by('id')
        else:
            if city_id is None or city_id == '':
                city_id = ''
                orgs_list = CourseOrg.objects.filter(category=ct).order_by('id')
            else:
                orgs_list = CourseOrg.objects.filter(category=ct, city_id=city_id).order_by('id')

        all_citys = CityDict.objects.all()
        org_nums = orgs_list.count()

        # 排序规则
        sort = request.GET.get('sort', 'default')
        if sort == 'students':
            orgs_list = orgs_list.order_by('-students')
        elif sort == 'courses':
            orgs_list = orgs_list.order_by('-fav_nums')
        else:
            orgs_list = orgs_list.order_by('-id')
        # 创建分页器对象
        page = request.GET.get('page')
        paginator = Paginator(orgs_list, 2)
        if page is None or page == '':

            all_orgs = paginator.page(1)
        else:
            all_orgs = paginator.page(page)

        # 查询指定分类的授课学校按照点击率排序显示2个
        hots = CourseOrg.objects.all().order_by('-click_nums')[0:2]
        hot_orgs = []
        for hot in hots:
            hot_orgs.append({
                'name': hot.name,
                'address': hot.address,
            })

        context = {
            'all_orgs': all_orgs,
            'hot_orgs': hot_orgs,
            'all_citys': all_citys,
            'org_nums': org_nums,
            'category': ct,
            'city_id': city_id
        }
        return render(request, 'org-list.html', context)


# 我要学习
class AddAskView(View):
    def post(self, request):
        # 接受
        name = request.POST.get('name')
        mobile = request.POST.get('mobile')
        course_name = request.POST.get('course_name')
        # 验证
        if not all([name, mobile, course_name]):
            return http.HttpResponseForbidden('填写数据不完整')
        # 验证电话号
        if not re.match('^1[3456789]\d{9}$', mobile):
            return http.HttpResponseForbidden('电话号错误')
        # 保存到数据库
        user = UserAsk.objects.create(name=name, mobile=mobile, course_name=course_name)
        user.save()
        # 响应
        return http.JsonResponse({'status': 'success'})


# 校区老师详情页
class DetailTeacher(View):
    def get(self, request, pk):
        try:
            teacher = Teacher.objects.get(id=pk)
        except:
            return render(request, '404.html')
        all_courses = teacher.course_set.all()
        sorted_teacher = Teacher.objects.all().order_by('-id')[0:2]
        user = request.user
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=pk, fav_type=3)
        except:
            has_teacher_faved = False
        else:
            has_teacher_faved = True
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=teacher.org_id, fav_type=2)
        except:
            has_org_faved = False
        else:
            has_org_faved = True

        context = {
            'teacher': teacher,
            'all_courses': all_courses,
            'sorted_teacher': sorted_teacher,
            'has_teacher_faved': has_teacher_faved,
            'has_org_faved': has_org_faved

        }
        return render(request, 'teacher-detail.html', context)


# 添加收藏  删除收藏

class AddFavView(View):
    def post(self, request):
        # 接受数据
        user = request.user
        fav_id = request.POST.get('fav_id')
        fav_type = request.POST.get('fav_type')
        if not request.user.is_authenticated:
            return http.JsonResponse({
                'status': 'fail',
                'msg': '用户未登录'
            })
        try:
            user = UserFavorite.objects.get(fav_type=fav_type, user_id=user.id, fav_id=fav_id)
            user.delete()
            msg = '已取消收藏'
        except:
            UserFavorite.objects.create(
                user_id=user.id,
                fav_id=fav_id,
                fav_type=fav_type)
            msg = '收藏成功'
        return http.JsonResponse({'msg': msg, 'status': 'success'})


# 教师列表页
class Teacher_listView(View):
    def get(self, request):
        # 创建分页器对象
        sort = request.GET.get('sort', 'default')
        if sort == 'hot':
            all_teachers = Teacher.objects.all().order_by('-click_nums')
        else:
            all_teachers = Teacher.objects.all().order_by('-id')

        page = request.GET.get('page')
        paginator = Paginator(all_teachers, 2)
        if page is None or page == '':

            all_teachers = paginator.page(1)
        else:
            all_teachers = paginator.page(page)

        # 查询指定分类的老师按照点击率排序显示2个
        teachers = Teacher.objects.all().order_by('id')[0:2]
        sorted_teacher = []
        for hot in teachers:
            sorted_teacher.append({
                'name': hot.name,
                'work_years': hot.work_years,
                'image': hot.image
            })

        context = {
            'all_teachers': all_teachers,
            'sorted_teacher': sorted_teacher
        }
        return render(request, 'teachers-list.html', context)


# 校区首页
class HomeView(View):
    def get(self, request, pk):
        # 查询学校
        courses = CourseOrg.objects.get(pk=pk)
        # 查询学校对应的课程
        all_courses = courses.course_set.all()
        # 查询学校对应的老师
        all_teachers = courses.teacher_set.all()
        # 学校是否已收藏
        user = request.user
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=pk, fav_type=2)
        except:
            has_fav = False
        else:
            has_fav = True

        context = {
            'org_id': courses.id,
            'course_org': courses,
            'all_courses': all_courses,
            'all_teachers': all_teachers,
            'has_fav': has_fav
        }

        return render(request, 'org-detail-homepage.html', context)


# 学校课程课程页
class CourseView(View):
    def get(self, request, pk):
        courses = CourseOrg.objects.get(pk=pk)
        # 查询学校对应的课程
        all_courses = courses.course_set.all()
        page = request.GET.get('page')
        all_courses = Paginator(all_courses, 2)
        if page is None or page == '':

            all_courses = all_courses.page(1)
        else:
            all_courses = all_courses.page(page)
        # 学校是否已收藏
        user = request.user
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=pk, fav_type=2)
        except:
            has_fav = False
        else:
            has_fav = True
        context = {
            'course_org': courses,
            'all_courses': all_courses,
            'has_fav': has_fav,
        }
        return render(request, 'org-detail-course.html', context)


# 学校介绍
class DescView(View):
    def get(self, request, pk):
        courses = CourseOrg.objects.get(pk=pk)
        # 学校是否已收藏
        user = request.user
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=pk, fav_type=2)
        except:
            has_fav = False
        else:
            has_fav = True
        context = {
            'course_org': courses,
            'has_fav': has_fav,
        }
        return render(request, 'org-detail-desc.html', context)


# 校区老师
class TeacherView(View):
    def get(self, request, pk):
        # 查询学校
        courses = CourseOrg.objects.get(pk=pk)
        # 查询学校关联的老师
        all_teachers = courses.teacher_set.all()
        # 学校是否已收藏
        user = request.user
        try:
            UserFavorite.objects.get(user_id=user.id, fav_id=pk, fav_type=2)
        except:
            has_fav = False
        else:
            has_fav = True

        context = {
            'course_org': courses,
            'all_teachers': all_teachers,
            'has_fav': has_fav,
        }

        return render(request, 'org-detail-teachers.html', context)
